import React, {Component} from "react";
import "./TopBar.css"
import {createTheme, styled, ThemeProvider} from '@mui/material/styles';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import SearchIcon from '@mui/icons-material/Search';
import {alpha, Box, Button, ButtonGroup, Grid, InputBase, Popover} from "@mui/material";
import {Link, Navigate} from "react-router-dom";
import PubSub from "pubsub-js";
import MenuIcon from '@mui/icons-material/Menu';
import FullscreenIcon from '@mui/icons-material/Fullscreen';
import MinimizeIcon from '@mui/icons-material/Minimize';
import FullscreenExitIcon from '@mui/icons-material/FullscreenExit';
import OpenInFullIcon from '@mui/icons-material/OpenInFull';
import CloseFullscreenIcon from '@mui/icons-material/CloseFullscreen';
import CloseIcon from '@mui/icons-material/Close';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import RefreshIcon from '@mui/icons-material/Refresh';

const ipcRenderer = window.ipcRenderer;
const theme = createTheme({
    palette: {
        secondary: {
            main: '#ff0202',
            contrastText: '#ff0202'
        },
        primary:{
            main:'#ffffff',
            contrastText:'#ffffff'
        }
    },

});
const Search = styled('div')(({ theme }) => ({
    position: 'relative',
    borderRadius: theme.shape.borderRadius,
    backgroundColor: alpha(theme.palette.common.white, 0.15),
    '&:hover': {
        backgroundColor: alpha(theme.palette.common.white, 0.25),
    },
    marginRight: theme.spacing(2),
    marginLeft: 0,
    width: '100%',
    [theme.breakpoints.up('sm')]: {
        marginLeft: theme.spacing(3),
        width: 'auto',
    },
}));

const SearchIconWrapper = styled('div')(({ theme }) => ({
    padding: theme.spacing(0, 2),
    height: '100%',
    position: 'absolute',
    pointerEvents: 'none',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}));

const StyledInputBase = styled(InputBase)(({ theme }) => ({
    color: 'inherit',
    '& .MuiInputBase-input': {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)})`,
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('md')]: {
            width: '20ch',
        },
    },
}));
export default class TopBar extends Component{

    state = {
        value:'1',
        toSearch:false,
        keywords:"",
        anchorEl:null,
        isMaximized:false,
        isFullScreen:false
    };
    key=0;
    componentDidMount() {
        this.key = PubSub.subscribe("changeTopBarByUrl",this.handleChangeByUrl);
        ipcRenderer.on('screenStatus',(e,r) => {
            //console.log(r)
               let isMax = r.isMaximized || false;
               let isFull = r.isFullScreen || false;
               this.setState({isMaximized:isMax,isFullScreen:isFull});
        })
    }
    componentWillUnmount() {
        PubSub.unsubscribe(this.key);
    }
    handleChangeByUrl = (msg,data) => {
        this.setState({value:data})
    }
    handleChange = (event, newValue) => {
        this.setState({value:newValue})
    };

    handleClick = (event) => {
        this.setState({anchorEl:event.currentTarget});
    };

    handleClose = () => {
        this.setState({anchorEl:null});
    };


    searchSubmit = (event) => {
        if(event.key === "Enter") {
            //console.log('@@@'+event.target.value)
            event.target.blur()
            this.setState({keywords:event.target.value})
            this.setState({toSearch:true})

        }
    }
    toSearch = (r) => {
        this.setState({toSearch:false})
        //console.log('leave')
        PubSub.publish('changSearchTopBar',0);
        PubSub.publish('changSearchKeyWorld',this.state.keywords);
        return <Navigate to='/search' state={{keywords:this.state.keywords}}/>
    }
    exitScreen = () => {
        ipcRenderer.send('exitScreen');
        this.setState({anchorEl:null});
    }
    minimizeScreen = () => {
        ipcRenderer.send('minimizeScreen');
        this.setState({anchorEl:null});
    }
    maximizeScreen = () => {
        ipcRenderer.send('maximizeScreen');
        this.setState({anchorEl:null});
    }
    fullScreen = () => {
        ipcRenderer.send('fullScreen');
        this.setState({anchorEl:null});
    }
    forward = () => {
        ipcRenderer.send('forward');
    }
    back = () => {
        ipcRenderer.send('back');
    }
    fresh = () => {
        ipcRenderer.send('fresh');
    }
    render() {
        var open = Boolean(this.state.anchorEl);
        var id = open ? 'simple-popover' : undefined;
        return (
            <header id='header'>
                <Grid container
                      direction="row"
                      justifyContent="center"
                      alignItems="center"
                >


                        <ThemeProvider theme={theme}>
                            <Grid   className='navs' item xs={2}>
                                <Search>
                                    <SearchIconWrapper>
                                        <SearchIcon />
                                    </SearchIconWrapper>
                                    <StyledInputBase
                                        onKeyDown={(e)=>this.searchSubmit(e)}
                                        placeholder="搜索歌曲"
                                        inputProps={{ 'aria-label': 'search' }}
                                    />
                                </Search>
                            </Grid>
                            <Grid item>

                                    <Tabs className='navs' textColor="inherit"  value={this.state.value} onChange={this.handleChange}
                                          indicatorColor='secondary'
                                          aria-label="nav tabs example">
                                        <Tab label="推荐" value="1" to="/recommend" component={Link} />
                                        <Tab label="歌单" value="2" to="/playlistPage" component={Link} />
                                        <Tab label="排行榜" value="3" to="/topList" component={Link} />
                                        <Tab label="歌手" value="4" to="/singerListPage" component={Link} />
                                    </Tabs>

                            </Grid>
                        </ThemeProvider>

                    {this.state.toSearch?this.toSearch():""}

                </Grid>
                <ThemeProvider theme={theme}>
                    <Button
                        color="primary"
                        aria-label="open drawer"
                        onClick={this.handleClick}
                        edge="start"
                        sx={{border:'1px solid rgba(255,255,255,0.1)',position:'absolute',right:5,top:5}}
                        className='navs'
                    >
                        <MenuIcon />
                    </Button>
                </ThemeProvider>
                    <Popover
                        id={id}
                        open={open}
                        anchorEl={this.state.anchorEl}
                        onClose={this.handleClose}
                        anchorOrigin={{
                            vertical: 'bottom',
                            horizontal: 'right',
                        }}
                        transformOrigin={{
                            vertical: 'top',
                            horizontal: 'right',
                        }}
                    >
                        <Box
                            sx={{
                                display: 'flex',
                                '& > *': {
                                    m: 1,
                                },
                            }}
                        >
                            <ButtonGroup
                                orientation="vertical"
                                aria-label="vertical contained button group"
                                variant="text"
                                color='inherit'
                            >
                                <Button onClick={this.exitScreen}><CloseIcon/>退出应用</Button>
                                <Button onClick={this.fullScreen}>{this.state.isFullScreen?<FullscreenExitIcon/>:<FullscreenIcon/>}{this.state.isFullScreen?'退出全屏':'全屏'}</Button>
                                <Button onClick={this.maximizeScreen}>{this.state.isMaximized?<CloseFullscreenIcon/>:<OpenInFullIcon/>}{this.state.isMaximized?'退出最大化':'最大化'}</Button>
                                <Button onClick={this.minimizeScreen}><MinimizeIcon/>最小化</Button>
                            </ButtonGroup>
                        </Box>
                    </Popover>
                <ThemeProvider theme={theme}>
                    <Box
                        sx={{position:'absolute',left:5,top:5}}
                    >
                        <Button
                            color="primary"
                            aria-label="open drawer"
                            onClick={this.back}
                            edge="start"

                            className='navs'
                        >
                            <ArrowBackIosNewIcon />
                        </Button>
                        <Button
                            color="primary"
                            aria-label="open drawer"
                            onClick={this.forward}
                            edge="start"
                            className='navs'
                        >
                            <ArrowForwardIosIcon />
                        </Button>
                        <Button
                            color="primary"
                            aria-label="open drawer"
                            onClick={this.fresh}
                            edge="start"
                            className='navs'
                        >
                            <RefreshIcon />
                        </Button>
                    </Box>
                </ThemeProvider>
            </header>
        );
    }

}
